package a_doubleWrite;

/**
 * 43. 字符串相乘
 * 给定两个以字符串形式表示的非负整数 num1 和 num2，返回 num1 和 num2 的乘积，它们的乘积也表示为字符串形式。
 * @author: luolidong
 * @create: 2021-07-21 09:46
 * @version: 1.0
 */
public class L43 {
    public String multiply(String num1, String num2) {
        if(num1.length()==0||num2.length()==0) return "";
        char[] arr1 = num1.toCharArray();
        char[] arr2 = num2.toCharArray();

        //1.arr1的每一位，与arr2相乘
//        1234
//          56

//        123456
//          234500
        String ans="";
        for (int i = arr1.length-1; i >=0 ; i--) {
            StringBuilder builder = new StringBuilder();
            //要添加的0
            for (int j = arr1.length-i-1; j >0 ; j--) {
                builder.append('0');
            }
            //转换
            int n1=arr1[i]-'0';
            int carry=0;
            int j=arr2.length-1;
            while (j>=0||carry!=0){
                int n2=j>=0? arr2[j]-'0':0;
                int sum=n1*n2+carry;
                carry=sum/10;
                builder.append(sum%10);
                j--;
            }
            ans=addString(builder.reverse().toString(),ans);
        }
        return ans;
    }

    private String addString(String num1, String num2) {
        StringBuilder builder = new StringBuilder();
        int carry=0;
        int i=num1.length()-1,j=num2.length()-1;
        while (i>=0||j>=0||carry!=0){
            int n1=i>=0? num1.charAt(i)-'0':0;
            int n2=j>=0? num2.charAt(j)-'0':0;
            int sum=(n1+n2+carry);
            carry=sum/10;
            builder.append(sum%10);
            i--;
            j--;
        }
        return builder.reverse().toString();
    }

    public static void main(String[] args) {
        L43 l43 = new L43();
        String s = l43.multiply("8765", "6745");
        System.out.println(8765*6745);
        System.out.println(s);
    }
}
